package com.treasure.hunt.task

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import android.os.CountDownTimer
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.*
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.android.material.tabs.TabLayout
import com.module.lemlin.base.loadCropImage
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.treasure.hunt.R
import com.treasure.hunt.app.AppConstance
import com.treasure.hunt.entity.LuckyGridList
import com.treasure.hunt.hunt.HuntGradeFragment
import com.treasure.hunt.mine.MineConfigActivity
import com.treasure.hunt.mode.LuckyViewMode
import com.treasure.hunt.popup.DialogFlopPopup
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.android.synthetic.main.activity_task_grid.*
import kotlinx.android.synthetic.main.include_task_grid.*
import java.util.concurrent.TimeUnit


class TaskGridActivity : ViewModeActivity<LuckyViewMode>() {

    companion object {
        fun open(activity: Activity) {
            val intent = Intent(activity, TaskGridActivity::class.java)
            activity.startActivity(intent)
        }
    }


    private val ranking: MutableList<String> = mutableListOf(
        "今日奖池", "今日排行"
    )

    private val flopPopup: DialogFlopPopup by lazy {
        DialogFlopPopup(context = this, onAnimationEnd = {})
    }

    private val gridAdapter =
        object : BaseQuickAdapter<LuckyGridList, BaseViewHolder>(R.layout.item_task_grid) {
            var posMap =
                mapOf(
                    0 to 0, 1 to 1, 2 to 2, 3 to 3, 4 to 4, 5 to 6,
                    6 to 8, 7 to 10, 8 to 12, 9 to 17, 10 to 16, 11 to 15,
                    12 to 14, 13 to 13, 14 to 11, 15 to 9, 16 to 7, 17 to 5
                )
            var selectedPosition = -1
                set(value) {
                    if (field != value) {
                        field = value
                        notifyDataSetChanged()
                    }
                }

            override fun convert(holder: BaseViewHolder, item: LuckyGridList) {
                holder.setText(R.id.tvTaskGridTitle, item.title)

                val isHttps: Boolean = item.image.substring(0, 5).contains("http") ||
                        item.image.substring(0, 5).contains("https")
                holder.getView<ImageView>(R.id.ivTaskGridIcon)
                    .loadCropImage("${if (isHttps) "" else AppConstance.URL_IMAGE}${item.image}")

                holder.getView<ImageView>(R.id.ivTaskGridIcon).layoutParams.apply {
                    val screen: Int = (ScreenUtils.getScreenWidth() - ConvertUtils.dp2px(60f)) / 5
                    width = screen
                    height = screen
                }

                holder.itemView.isSelected = holder.layoutPosition == selectedPosition
            }

            fun reversePosition(selectPos: Int): Int {
                for ((key: Int, value: Int) in posMap.entries) {
                    if (key == selectPos) return value
                }
                return -1
            }

            fun currentPosition(currentPos: Int): Int {
                for ((key: Int, value: Int) in posMap.entries) {
                    if (value == currentPos) return key
                }
                return -1
            }

            fun currentPosition(): Int {
                return currentPosition(selectedPosition)
            }
        }

    private var mCountDownDisposable: Disposable? = null

    override val layoutResId: Int
        get() = R.layout.activity_task_grid

    override fun viewModel(): LuckyViewMode {
        return createViewModel()
    }

    override fun stateBar(): StatusBar {
        return StatusBar(
            isLightMode = false,
            bottomColor = R.color.FF_201E43,
            view = flTaskGridBar
        )
    }

    override fun initView() {
        rvTaskGridBody.apply {
            val layoutManager = GridLayoutManager(this@TaskGridActivity as Context, 5)
            layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    return if (position == 5 || position == 7 || position == 9 || position == 11) 4 else 1
                }
            }
            this.layoutManager = layoutManager

        }.adapter = gridAdapter

        val screen: Int = (ScreenUtils.getScreenWidth() - ConvertUtils.dp2px(60f)) / 5
        includeTaskGrid.setPadding(
            screen + ConvertUtils.dp2px(15f),
            screen + ConvertUtils.dp2px(38f),
            screen + ConvertUtils.dp2px(15f),
            screen + ConvertUtils.dp2px(38f)
        )

        ivTaskGridBack.setOnClickListener { finish() }

        tvTaskGridRule.setOnClickListener {
            MineConfigActivity.open(activity = this, title = "九色格规则", name = "turntable_video_rule")
        }

        ivTaskRankingHelp.setOnClickListener {
            MineConfigActivity.open(activity = this, title = "温馨提示", name = "daily_rule")
        }

        tvTaskGridLucky.setOnClickListener {
            ivTaskGridDice.setBackgroundResource(R.drawable.dice_show)
            tvTaskGridLucky.isEnabled = false
            viewModel.luckyTurntableWinningThePrize()

//            mCountDownTimer.cancel()
        }

        tvTaskGridPhysicalStrengthAdd.setOnClickListener {
            val maps: MutableMap<String, Any?> = mutableMapOf(
                "advertisement_type" to 5,
                "luck_draw_type" to 3
            )
            viewModel.videoType(maps)

//            mCountDownTimer.start()
        }



        tlTaskRankingLabel.apply {
            addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabReselected(tab: TabLayout.Tab?) = Unit

                override fun onTabUnselected(tab: TabLayout.Tab?) {
                    tab?.customView = null
                }

                override fun onTabSelected(tab: TabLayout.Tab?) {
                    val text: TextView = TextView(context).apply {
                        layoutParams = LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.MATCH_PARENT
                        )
                        setTextColor(ColorUtils.getColor(R.color.white))
                        setBackgroundResource(R.color.FF_4F4C84)
                        gravity = Gravity.CENTER
                    }
                    text.text = tab?.text
                    tab?.customView = text
                }
            })
        }.setupWithViewPager(vpTaskRankingBody.apply {
            adapter = object : FragmentStatePagerAdapter(
                supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
            ) {
                override fun getItem(position: Int): Fragment =
                    if (position == 0) GridPrizePoolFragment.newInstance() else GridRankingFragment.newInstance()

                override fun getCount(): Int = ranking.size

                override fun getPageTitle(position: Int): CharSequence? {
                    return ranking[position]
                }

                override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {}
            }
        })

    }

    override fun initData() {

        viewModel.luckyTurntable()

        viewModel.luckyGetLuckDraw(3)
    }

    override fun initViewMode() {

        viewModel.luckyGridListLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.throwable?.msg ?: "未知错误")
            }
            if (response.status != Status.SUCCESS)
                return@Observer

            response.httpData?.data?.let {
                if (it.list.size == 0) {
                    return@Observer
                }
                if (it.list.size < 18) {
                    includeTaskGrid.visibility = View.INVISIBLE
                    toast("抽奖数据不完整")
                    return@Observer
                } else {
                    includeTaskGrid.visibility = View.VISIBLE
                }
                val newList: MutableList<LuckyGridList> = mutableListOf()
                val mapLuckyList: MutableMap<Int, LuckyGridList> = mutableMapOf()
                for (index: Int in it.list.indices) {
                    mapLuckyList[index] = it.list[gridAdapter.currentPosition(index)]
                }

                for ((key: Int, value: LuckyGridList) in mapLuckyList.entries) {
                    newList.add(value)
                }

                gridAdapter.setNewInstance(newList)
                gridAdapter.selectedPosition = gridAdapter.reversePosition(it.point)

                tvTaskClearanceNum.text = "今日通关次数：${it.user_num}"
            }
        })

        viewModel.luckyGridLiveData.observe(this, Observer { response ->

            when (response.status) {
                Status.START -> {
                    (ivTaskGridDice.background as AnimationDrawable).start()
                }
                Status.FAILURE -> {
                    tvTaskGridLucky.isEnabled = true
                    (ivTaskGridDice.background as AnimationDrawable).stop()
                    toast(response.throwable?.msg ?: "未知错误")
                }
                Status.SUCCESS -> {
                    tvTaskGridLucky.isEnabled = true
                    (ivTaskGridDice.background as AnimationDrawable).stop()
                    response.httpData?.data?.let {
                        val position: Int = it.point
                        val currentPosition: Int = gridAdapter.currentPosition()
                        val pos: MutableList<Int> = mutableListOf()
                        if (position - currentPosition < 0) {
                            for (index: Int in (currentPosition + 1) until gridAdapter.data.size)
                                pos.add(index)
                            for (index: Int in 0..position)
                                pos.add(index)
                        } else for (index: Int in (currentPosition + 1)..position) {
                            pos.add(index)
                        }
                        val disposable: Disposable =
                            Flowable.intervalRange(
                                (0), pos.size.toLong(), (0), (350), TimeUnit.MILLISECONDS
                            ).observeOn(AndroidSchedulers.mainThread())
                                .doOnNext { long ->
                                    gridAdapter.selectedPosition =
                                        gridAdapter.reversePosition(pos[long.toInt()])
                                }
                                .doOnComplete {
                                    flopPopup.fillData(it).showPopupWindow()
                                    viewModel.videoNoReward(advertisementType = 3)
                                }
                                .subscribe()

                        ivTaskGridDice.setBackgroundResource(
                            when (it.spot) {
                                1 -> R.mipmap.ic_23215
                                2 -> R.mipmap.ic_23254
                                3 -> R.mipmap.ic_23260
                                4 -> R.mipmap.ic_23266
                                5 -> R.mipmap.ic_23267
                                else -> R.mipmap.ic_23275
                            }
                        )

                        viewModel.dispose.add(disposable)
                        viewModel.luckyGetLuckDraw(3)
                    }
                }
            }
        })

        viewModel.luckyNumLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.throwable?.msg ?: "未知错误")
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let { luckyNum ->
                tvTaskGridConsume.text = "每次消耗体力值${luckyNum.consume}点"
                tvTaskGridReplyVolume.text = "恢复${luckyNum.reply_volume}点体力倒计时"
                tvTaskGridPhysicalStrength.text = "体力${luckyNum.num}/${luckyNum.physical_strength}"
                pbTaskGridProgress.max = luckyNum.physical_strength
                pbTaskGridProgress.progress = luckyNum.num
                mCountDownDisposable?.dispose()
                tvTaskGridDownTime.text = "00:00:00"
                if (luckyNum.num >= luckyNum.physical_strength)
                    return@Observer
                countDownTime(luckyNum.count_down)
            }
        })

        viewModel.videoTypeLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
                ?: return@Observer
            val codeId: String? = response.httpData?.data?.advertising_space
            if (codeId == null) {
                toast("广告位ID为空")
            } else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdCSJ(mActivity = this, codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdYLH(mActivity = this, codeId = codeId)
            }
        })

        viewModel.videoEndLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let {
                flopPopup.fillData(it.data).showPopupWindow()
                viewModel.videoNoReward(advertisementType = 3)
                viewModel.luckyGetLuckDraw(3)
            }
        })

        viewModel.videoNoRewardLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
            val codeId: String? = response.httpData?.data?.advertising_space
            if (cid == null) {

            } else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdCSJ(mActivity = this, codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdYLH(mActivity = this, codeId = codeId)
            }
        })

        viewModel.rewardVerifyAdLiveData.observe(this, Observer { isRewardVerify ->
            if (!isRewardVerify)
                return@Observer
            viewModel.videoTypeLiveData.value?.httpData?.data?.let {
                viewModel.videoEnd(it.video_log_id)
            }
        })

        viewModel.viewAdLiveData.observe(this, Observer { view ->
            view?.let {
                flopPopup.fillViewAd(view)
            }
        })
    }

    private fun countDownTime(countDown: Long) {
        mCountDownDisposable = Flowable.intervalRange(1, countDown, 0, 1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext {
                val remnant: Long = countDown - it
                val hour: String = getHours(remnant)
                val mins: String = getMins(remnant)
                val second: String = getSeconds(remnant)
                tvTaskGridDownTime.text = "${hour}:${mins}:${second}"
            }
            .doOnComplete {
                viewModel.luckyGetLuckDraw(3)
                tvTaskGridDownTime.text = "00:00:00"
            }
            .subscribe()
        viewModel.dispose.add(mCountDownDisposable)
    }


    private fun getHours(second: Long): String { //计算秒有多少小时
        var h: Long = 0
        if (second > 3600) {
            h = second / 3600
        }
        return if (h < 10) "0${h}" else h.toString()
    }

    private fun getMins(second: Long): String { //计算秒有多少分
        var d: Long = 0
        val temp = second % 3600
        if (second > 3600) {
            if (temp != 0L) {
                if (temp > 60) {
                    d = temp / 60
                }
            }
        } else {
            d = second / 60
        }
        return if (d < 10) "0${d}" else d.toString()
    }

    private fun getSeconds(second: Long): String { //计算秒有多少秒
        var s: Long = 0
        val temp = second % 3600
        if (second > 3600) {
            if (temp != 0L) {
                if (temp > 60) {
                    if (temp % 60 != 0L) {
                        s = temp % 60
                    }
                } else {
                    s = temp
                }
            }
        } else {
            if (second % 60 != 0L) {
                s = second % 60
            }
        }
        return if (s < 10) "0${s}" else s.toString()
    }
}